<%@ page import="com.zwy.Shopping.model.Product" %>
<%@ page import="com.zwy.Shopping.dao.ProductDao" %>
<%@ page import="com.zwy.Shopping.dao.impl.ProductDaoImpl" %>
<%@ page import="java.util.List" %>
<%@ page import="com.zwy.Shopping.model.Category" %>
<%@ page import="com.zwy.Shopping.model.CartItem" %>
<%@ page import="java.util.ArrayList" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/bootstrap.bundle.js"></script>
<script>
    function buyProductNow(productId){
        //使用AJAX发送请求到服务器
        //先创建一个XMLHttpRequest();对象,该对象可以在不刷新页面的情况请求特定的url(地址栏的信息)
        var xhr = new XMLHttpRequest();
        xhr.open("POST","now_shopping_get_product",true)//Servlet的映射路径是 now_shopping
        //设置请求头,Content-Type是key请求体格式,application/x-www-form-urlencoded是value,具体的请求体格式,表单格式
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        //回调函数监听readystate的变化,每变化一次就调用方法一次
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 0) {
                console.log("请求还初始化");
                // 这里可以处理服务器的响应，或者进行页面刷新等操作
            }
            if (xhr.readyState === 1) {
                console.log("服务器已经建立链接");
                // 这里可以处理服务器的响应，或者进行页面刷新等操作
            }
            if (xhr.readyState === 2 ) {
                console.log("请求已接受");
                // 这里可以处理服务器的响应，或者进行页面刷新等操作
            }
            if (xhr.readyState === 3) {
                console.log("请求处理中");
                // 这里可以处理服务器的响应，或者进行页面刷新等操作
            }
            if (xhr.readyState === 4) {
                console.log("请求已完成,且相应已就绪");
                // 这里可以处理服务器的响应，或者进行页面刷新等操作
            }
        };
        xhr.send("productId=" + productId); // 发送产品ID到服务器
    }
    function addShoppingCar(productId){
        var xhr = new XMLHttpRequest();
        xhr.open("post","add_shopping_car",true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {//回调函数,readystate改变调用
            if (xhr.readyState === 4 && xhr.status === 200) {
                //请求完成后更新界面,这里仅仅改变nav.jsp的购物车旁的徽章数字(消息提示)
                location.reload();
                console.log(xhr.responseText); // 打印服务器的响应内容
                // 在这里您可以处理响应，比如更新页面上的某些元素
            } else if (xhr.readyState === 4 && xhr.status !== 200) {
                // 请求已完成但出现了错误
                console.error("请求失败: " + xhr.statusText);
            }
        };
        xhr.send("productId=" + productId);
    }
</script>
<style>
    .product_img{
        width: 80%;
        height: 60%;
    }
</style>
<head>
    <meta charset="UTF-8">
    <title>用户首页</title>
<jsp:include page="includes/nav.jsp"></jsp:include>
</head>
<body>

<%
    //设施request参数
    String search = request.getParameter("search");
    String categoryId = request.getParameter("categoryId");

    ProductDao productDao = new ProductDaoImpl();
    List<Category> categories = productDao.getAllCategories();


%>

    <nav class="navbar navbar-expand-sm bg-primary navbar-dark " style="margin-top: 40px;">
        <ul class="navbar-nav">
            <li class="nav-item active">
                <a class="nav-link " href="index.jsp">最近热买</a>
            </li>
            <%for(Category category: categories){%>
            <li class="nav-item">
                <a class="nav-link "href="index.jsp?categoryId=<%=category.getId()%>"><%=category.getName()%></a>
            </li>
            <%}%>
        </ul>
<!--        搜索框-->
        <form class="d-flex" method="get" >
            <input class="form-control me-2" type="text" placeholder="Search" name="search">
            <button class="btn btn-primary" type="submit"><img class="rounded img-fluid bg-primary" src="img/search.png"></button>
        </form>
    </nav>
<div class="container-fluid mt-3">
    <!-- 轮播 -->
    <div id="demo" class="carousel slide" data-bs-ride="carousel">

        <!-- 指示符 -->
        <div class="carousel-indicators">
            <button type="button" data-bs-target="#demo" data-bs-slide-to="0" class="active"></button>
            <button type="button" data-bs-target="#demo" data-bs-slide-to="1"></button>
            <button type="button" data-bs-target="#demo" data-bs-slide-to="2"></button>
        </div>

        <!-- 轮播图片 -->
        <div class="carousel-inner">
            <div class="carousel-item active">
                <img src="img/smoking-e-cigarette.jpg" class="d-block" style="width:100%">
            </div>
            <div class="carousel-item">
                <img src="img/female-shoes.jpg" class="d-block" style="width:100%">
            </div>
            <div class="carousel-item">
                <img src="img/ladis-bag.jpg" class="d-block" style="width:100%">
            </div>
        </div>

        <!-- 左右切换按钮 -->
        <button class="carousel-control-prev" type="button" data-bs-target="#demo" data-bs-slide="prev">
            <span class="carousel-control-prev-icon"></span>
        </button>
        <button class="carousel-control-next" type="button" data-bs-target="#demo" data-bs-slide="next">
            <span class="carousel-control-next-icon"></span>
        </button>
    </div>
    <div class="row">
        <% List<Product> products;
        if(search != null){
            //模糊查询
            products = productDao.getProduct(search);
        }else if(categoryId != null){
            products = productDao.getProduct(Integer.parseInt(categoryId));
        }else {
            products = productDao.getAllProduct();
        }
        //商品对象集不为空
        if(!products.isEmpty()){
            for(Product p : products){%>
                 <div class="col-sm-4 ">
            <div class="card  m-3 bg-info " >

                <div class="card-img-top d-flex m-auto"><img class="product_img m-auto"  src="img/<%=p.getImage()%>" ></div>
                <div class="card-body">
                <div class="card-title "><%=p.getName()%></div>
                    <div class="card-text" style="align-content: center">
                    <label>市价:<s><%=p.getMarketPrice()%>元</s></label>
                    <label>售价:<%=p.getPrice()%>元</label>
                    <label>销量:<%=p.getSales()%>件</label>
                    <label>仅剩:<%=p.getStock()%>件</label>
                    </div>
                <div class="card-footer border-0 ">
                                            <%--点击链接先出发函数然后在进入链接 --%>
                    <%
//                        CartItem cartItem = new CartItem();
//                        application.setAttribute("cartItem",cartItem);
                        //根据判断application域对象cartItemList是否存在来确定是否创建一个application域对象cartItemList
                        List<CartItem> cartItemList = new ArrayList<>();
                        if(application.getAttribute("cartItemList")==null){
                        application.setAttribute("cartItemList",cartItemList);
                        }
                    %>
                    <a class="btn btn-primary" href="now_shopping.jsp" onclick="buyProductNow(<%=p.getId()%>)">立即购买</a>
                    <btn class="btn btn-secondary" onclick="addShoppingCar(<%=p.getId()%>)">加入购物车</btn>


                </div>
                </div>
            </div>
        </div>
            <%}%>
        <%}%>

</div>
</div>

</body>
</html>